package leetCode;

public class ReverseWords {
	
    public String reverseStr(String s, int k) {
    	char[] chars=s.toCharArray();
    	int i=0;
    	while (i<s.length()) {
    		if(i+k>s.length()){//剩下的<k个
    			myReverse(chars, i, s.length()-1);
    		}
    		//否则逆序k个
			myReverse(chars, i, i+k-1);
			i+=(2*k);
		}
		return String.copyValueOf(chars);
    }
    
    private void myReverse(char[] chars,int start,int end) {
    	while (start<end) {
    		char tmp=chars[start];
    		chars[start]=chars[end];
    		chars[end]=tmp;
    		start++;
    		end--;
		}
	}
    
    public static String reverseWords(String s) {
        StringBuilder result=new StringBuilder(s.length());
        int i=0,start;
        while(i<s.length()){
            start=i;
            while(i<s.length()&&s.charAt(i)!=' '){
                i++;
            }
            int j=i-1;
            while(j>=start){
                result.append(s.charAt(j));
                j--;
            }
            if(i<s.length()){
                result.append(' ');
                i++;
            }
        }
        return result.toString();
    }
    public static void main(String[] args) {
//		System.out.println(reverseWords("Let's take LeetCode contest"));
		ReverseWords reverseWords=new ReverseWords();
		System.out.println(reverseWords.reverseStr("abcdefg", 2));;
	}
}
